package th.retrofit.lib;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
 * 给定一个二叉树，返回其节点值自底向上的层序遍历。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）
 */
public class Solution107 {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Deque<List<Integer>> deque = new LinkedList<>();
        if (root == null) return (List<List<Integer>>)deque;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> result = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                result.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            deque.offerFirst(result);
        }
        return (List<List<Integer>>)deque;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,4,5,6,7,8};
        TreeNode[] nodes = new TreeNode[arr.length];
        for (int i = 0; i < arr.length; i++) {
            nodes[i] = new TreeNode(arr[i]);
        }
        TreeNode root = TreeNode.array2Tree(nodes);
        System.out.println(root);
        List<List<Integer>> results = new Solution107().levelOrderBottom(root);
        results.forEach(it -> {
            for (int i = 0; i < it.size(); i++) {
                System.out.print(it.get(i));
                System.out.print(",");
            }
            System.out.println();
        });
    }

}
